package com.kinon.ceshiaccount.fragment.home;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.adapter.DiningTypeAdapter;
import com.kinon.ceshiaccount.adapter.LunchAdapter;
import com.kinon.ceshiaccount.adapter.urgent.U_LunchAdapter;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.bean.RoleBean;
import com.kinon.ceshiaccount.bean.base.LunchBean;
import com.kinon.ceshiaccount.bean.urgent.Card;
import com.kinon.ceshiaccount.bean.urgent.U_SettletmentBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.fragment.BaseFragment;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.sunmi.SunmiSdkManage;
import com.kinon.ceshiaccount.util.LunchTypeUtil;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.util.SoundPoolManage;
import com.kinon.ceshiaccount.util.SysTimeManage;
import com.kinon.ceshiaccount.view.CustomDialog;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.module.fingerprintreader.FingerprintCaptureListener;
import com.zkteco.android.biometric.module.fingerprintreader.FingerprintSensor;
import com.zkteco.android.biometric.module.fingerprintreader.FingprintFactory;
import com.zkteco.android.biometric.module.fingerprintreader.ZKFingerService;
import com.zkteco.android.biometric.module.fingerprintreader.exception.FingerprintException;

import org.json.JSONArray;
import org.json.JSONException;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Response;
import sunmi.ds.callback.ISendCallback;

import static org.litepal.crud.DataSupport.where;

/**
 * Created by luohao on 2017-06-16.
 * 午餐界面
 */

public class FingerEatFragment extends BaseFragment implements View.OnClickListener{
    private View mView;
    /**餐卡id*/
    private EditText et_lunchId;
    /**午餐人数*/
    private TextView tv_lunchNum;
    /**午餐就餐信息*/
    private ListView list_lunch;
    /**显示就餐类型的布局*/
    private RelativeLayout rl_select;
    /**选择就餐类型*/
    private GridView grid_diningType;
    /**显示就餐类型*/
    private TextView tv_lunchType;

    private Button btn_clearCard;

    private LunchAdapter adapter=null;
    private ArrayList<LunchBean> lunchList=null;

    public static int amount=0;

    private Context context;

    //紧急情况下使用的数据
    ArrayList<U_SettletmentBean> selist;
    U_LunchAdapter uWAdapter=null;


    /**唯一标识*/
    private long nonce_str;
    private String on_card="";

    /**就餐类型*/
    private int mType=0;
    private ArrayList<RoleBean> binings=null;
    private DiningTypeAdapter diningAdapter=null;
    private int mIndex=0;
    /**第一次进入的时间*/
    private long firstTime;
    private String mLunchStrType="";
    Gson gson=new Gson();

    private FingerprintSensor mFingerPrintSensor=null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        mView=inflater.inflate(R.layout.fragment_lunch_layout,container,false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context= AccountApplication.getInstance();
        initView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            entryFingerPrint();

            et_lunchId.setText("");
            setCardnull();
            if(!Constant.URGENT_TYPE){
                tv_lunchNum.setText("人次：" + amount);
                adapter=new LunchAdapter(getActivity(),lunchList);
                list_lunch.setAdapter(adapter);
            }else{
                //紧急情况下
                getlunchNum();
            }
            if(binings!=null && diningAdapter!=null){
                int timeArea= (int)((System.currentTimeMillis()-firstTime)/(1000*60*60));
                setDiningType();
                if(timeArea>=2){
                    dialogSelect();
                }
            }
        }else{
            stopFingerPrint();
        }

    }

    /**获取默认的刷卡类型*/
    private void setDiningType(){
        int  type=SysTimeManage.getInstage().getOrderType(System.currentTimeMillis());
        for(int i=0;i<binings.size();i++){
            if(binings.get(i).getId()==type){
                mIndex=i;
                mType=type;
                continue;
            }
        }
        diningAdapter.selectItem(mIndex);
        diningAdapter.notifyDataSetChanged();
        tv_lunchType.setText(LunchTypeUtil.lunchType(mType));
    }

    private void initView() {
        et_lunchId= (EditText) mView.findViewById(R.id.et_lunchId);
        tv_lunchNum= (TextView) mView.findViewById(R.id.tv_lunchNum);
        list_lunch= (ListView) mView.findViewById(R.id.list_lunch);
        grid_diningType= (GridView) mView.findViewById(R.id.grid_diningType);
        rl_select= (RelativeLayout) mView.findViewById(R.id.rl_select);
        btn_clearCard= (Button) mView.findViewById(R.id.btn_clearCard);
        tv_lunchType= (TextView) mView.findViewById(R.id.tv_lunchType);

        et_lunchId.requestFocus();
        et_lunchId.setVisibility(View.GONE);
        btn_clearCard.setVisibility(View.GONE);
//        et_lunchId.addTextChangedListener(tWatcher);
        btn_clearCard.setOnClickListener(this);
        showDiningType();
        tv_lunchType.setText(LunchTypeUtil.lunchType(mType));

        lunchList=new ArrayList<>();

        if(!Constant.URGENT_TYPE){
            tv_lunchNum.setText("人次：" + amount);
            adapter=new LunchAdapter(getActivity(),lunchList);
            list_lunch.setAdapter(adapter);

        }else{
            //紧急情况下
            getlunchNum();
        }

        entryFingerPrint();

    }

    private void entryFingerPrint() {
        Map mFingerMap=new HashMap();
        mFingerMap.put(ParameterHelper.PARAM_KEY_VID,6997);
        mFingerMap.put(ParameterHelper.PARAM_KEY_PID, 288);

        mFingerPrintSensor= FingprintFactory.createFingerprintSensor(mContext,
                TransportType.USB,mFingerMap);
        getFinger();
    }

    private void getFinger(){
        beginFingerPrint();
        ArrayList<Card> cards= (ArrayList<Card>) DataSupport.findAll(Card.class,true);
        for(Card card:cards){
            card.save();
            if(null!=card.getFinger()&& !"".equals(card.getFinger())&&
                    null!=card.getNo()&& !"".equals(card.getNo())){
                byte[] reg= Base64.decode(card.getFinger(),Base64.NO_WRAP);
                ZKFingerService.save(reg,card.getNo());
            }
        }
        Log.e("lh", "count== "+ZKFingerService.count());

    }

    private void beginFingerPrint(){
        try {
            mFingerPrintSensor.open(0);
            mFingerPrintSensor.setFingerprintCaptureListener(0,fingerListener);
            mFingerPrintSensor.setFakeFunOn(1);
            mFingerPrintSensor.startCapture(0);
        } catch (FingerprintException e) {
            e.printStackTrace();
        }
    }

    private void stopFingerPrint(){
        try {
            mFingerPrintSensor.stopCapture(0);
            mFingerPrintSensor.close(0);

        } catch (FingerprintException e) {
            e.printStackTrace();
            Toast.makeText(mContext,"停止失败："+e.getErrorCode(),
                    Toast.LENGTH_SHORT).show();
        }
    }

    FingerprintCaptureListener fingerListener=new FingerprintCaptureListener() {
        //采集图像成功
        @Override
        public void captureOK(final byte[] bytes) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                }
            });
        }
        //采集图像失败
        @Override
        public void captureError(final FingerprintException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                }
            });

        }
        //采集模板成功 fpTemplate指纹模板
        @Override
        public void extractOK(final byte[] fpTemplate) {
            final byte[] tmpBuffer = fpTemplate;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    Log.e("lh", "extractOK:fpTemplate== "+tmpBuffer.length +"\n=="
//                            +fpTemplate.toString());
//                    tv_hint.setText("采集模板成功");
                        byte[] bufids = new byte[256];
                        //返回的对比指纹
                        int ret = ZKFingerService.identify(tmpBuffer, bufids, 55, 1);
                        if(ret>0){
                            //对比成功"识别成功："+"userID="
//                                    +strRes[0]+"指纹符合度"+strRes[1]+"%"
                            String strRes[] = new String(bufids).split("\t");
                            if (!Constant.URGENT_TYPE) {
                                lunchPay(strRes[0]);
                            }else{
                                addSqlit(strRes[0],"");
                            }
                        }

                }
            });
        }
        //提取模板失败
        @Override
        public void extractError(final int i) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //提取失败
                }
            });
        }
    };

    private void showDiningType(){
        String roles=SPManage.getInstance().getString("roles");
        if (TextUtils.isEmpty(roles)){
            return;
        }
        Gson gson=new Gson();
         binings=new ArrayList<>();
        try {
            JSONArray array=new JSONArray(roles);
            for(int i=0;i<array.length();i++){
                RoleBean bean=gson.fromJson(array.get(i).toString(),RoleBean.class);
                //显示固定的几种
                if(bean.getId()==0 || bean.getId()==1 ||bean.getId()==2
                        ||bean.getId()==3 ||bean.getId()==6) {
                    binings.add(bean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if(binings.size()==0){
            rl_select.setVisibility(View.GONE);
            return;
        }

        mType=binings.get(0).getId();
        if(binings.size()<=1){
            rl_select.setVisibility(View.GONE);
            return;
        }

        grid_diningType.setFocusable(false);
        grid_diningType.setNumColumns(binings.size());
         diningAdapter=new DiningTypeAdapter(context,binings);
        grid_diningType.setAdapter(diningAdapter);
        setDiningType();
        dialogSelect();
        grid_diningType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mIndex=i;
                mType=binings.get(i).getId();
                tv_lunchType.setText(LunchTypeUtil.lunchType(mType));
                diningAdapter.selectItem(i);
                diningAdapter.notifyDataSetChanged();

            }
        });

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_clearCard:
                et_lunchId.setText("");
                et_lunchId.requestFocus();
                break;
        }
    }

    /**
     * dialog选择就餐类型
     */
    private void dialogSelect(){
        firstTime=System.currentTimeMillis();
        CustomDialog dialog=new CustomDialog(1, getContext(),"请选择就餐类型", binings,
                mIndex,new CustomDialog.DialogClickListener() {
                    @Override
                    public void onDialogClick(int btn) {
                        mIndex=btn;
                        mType=binings.get(btn).getId();
                        tv_lunchType.setText(LunchTypeUtil.lunchType(mType));
//                        mLunchStrType=binings.get(btn).getName()+"人次:";
                        diningAdapter.selectItem(btn);
                        diningAdapter.notifyDataSetChanged();
                    }
                });
        dialog.show();
    }


    /**计算午餐人数*/
    private void getlunchNum(){
        long sysTime=System.currentTimeMillis();
        String date= SysTimeManage.getInstage().getDate(sysTime);
        amount = where("date = ? and type=?", date,"1").count(U_SettletmentBean.class);
        tv_lunchNum.setText("人次：" + amount);
        selist=new ArrayList<>();
        uWAdapter=new U_LunchAdapter(getContext(),selist);
        list_lunch.setAdapter(uWAdapter);
    }




    private TextWatcher tWatcher=new TextWatcher() {
        //text  输入框中改变前的字符串信息 start 输入框中改变后的字符串的起始位置
        // count输入框中改变前的字符串的位置 默认为0 after 输入框中改变后的一共输入字符串的数量
        @Override
        public void beforeTextChanged(CharSequence text, int start,
                                      int icount, int iafter) {
        }
        @Override
        public void onTextChanged(CharSequence text, int start,
                                  int icount, int iafter) {
            if(start==Constant.CARD_LENGTH-1) {
                String card = text.toString();
                if (!Constant.URGENT_TYPE) {
                    lunchPay(card);
                }else{
                    addSqlit(card,"");
                }
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    /**紧急模式下将数据加人数据库*/

    private void addSqlit(String card,String nonce_str){
        synchronized(card){
            et_lunchId.setText("");
//            int cardnub= DataSupport.where("no = ?",card).count(Card.class);
            ArrayList<Card> cardList= (ArrayList<Card>)
                    DataSupport.where("no = ?",card).find(Card.class);
            if(cardList==null ||cardList.size()<1){
                SoundPoolManage.getInstance().soundpPlay(2);
                et_lunchId.setText("");
                showScreen("","刷卡频率过快或付款码无效");
                Toast.makeText(context,"刷卡频率过快或付款码无效",Toast.LENGTH_SHORT).show();
                return;
            }
            long sysTime=System.currentTimeMillis();
            String date=SysTimeManage.getInstage().getDate(sysTime);

//            int num= DataSupport.where("card = ? and type = ? and date=?" ,card,"1",date )
//                    .count(U_SettletmentBean.class);
            int num=0;
            if(num<=2){
                String id= SysTimeManage.getInstage().getOrderId(sysTime);
//                int type=SysTimeManage.getInstage().getOrderType(sysTime);
                String time=SysTimeManage.getInstage().getDateTime(sysTime);
                U_SettletmentBean settl=new U_SettletmentBean(id,cardList.get(0).getName(),
                        mType,"0",time,0,num+1,0,date,0,nonce_str);
                boolean save= settl.save();
                if(save){
                    SoundPoolManage.getInstance().soundpPlay(1);
                    amount = amount + 1;
                    tv_lunchNum.setText("人次：" + amount);
                    Toast.makeText(context,"支付成功",Toast.LENGTH_SHORT).show();
                    showScreen("","支付成功");
                    if(!"".equals(nonce_str)){
                        int cardNum=1;
                        for(LunchBean l:lunchList){
                            if(card.equals(l.getNo())){
                                cardNum=l.getNum()+1;
                                Log.e("lh", "");

                            }
                        }
                        lunchList.add(0,new LunchBean(cardList.get(0).getName(),
                                cardNum,"离线","0",mType,0,card));
                        adapter.notifyDataSetChanged();
                        return;
                    }
                    selist.add(0,settl);
                    uWAdapter.notifyDataSetChanged();
                }else{
                    SoundPoolManage.getInstance().soundpPlay(2);
                    showScreen("","支付失败");
                    Toast.makeText(context,"刷卡失败",Toast.LENGTH_SHORT).show();
                }
            }else{
                showScreen("","您已支付满三次");
                Toast.makeText(context,"您已支付满三次",Toast.LENGTH_SHORT).show();
            }
        }

    }

    private void lunchPay(final String id){
        synchronized (id){
            et_lunchId.setText("");
            if(id.equals(on_card) &&
                    System.currentTimeMillis()-nonce_str<750){
                Toast.makeText(mContext,"刷卡频率过快",Toast.LENGTH_SHORT).show();
                return;
            }
            on_card=id;
            nonce_str=System.currentTimeMillis();

            Call<String> call= HttpManage.getReqLunchApi().
                    lunchPay(SPManage.getInstance().getToken(),id,mType+"",""+nonce_str);
            call.enqueue(new StrCallback<String>() {
                @Override
                public void onSuccess(Response<String> response, String base) {
                    SoundPoolManage.getInstance().soundpPlay(1);
                    LunchBean lunch=gson.fromJson(base,
                            LunchBean.class);
                        amount+=1;
                        lunchList.add(0,lunch);
                        if(lunchList.size()>31){
                            lunchList.remove(31);
                        }
                        if(lunch.getType()==0){
                            showScreen("姓名:"+lunch.getName(),"支付金额:"+lunch.getTotal()+
                                    "\n余额:"+lunch.getBalance());
                        }else {
                            showScreen("支付成功","剩余次数:"+lunch.getLeft());
                        }

                        adapter.notifyDataSetChanged();
                        tv_lunchNum.setText("人次:"+amount);
//                        setCardnull();
                }

                @Override
                public void onError(int code, String error) {

                    et_lunchId.setText("");
                    //超时默认成功
                if(code==Constant.ERROR_TIMEOUT_CODE){
                    addSqlit(id,""+nonce_str);

                }else{
                    SoundPoolManage.getInstance().soundpPlay(2);
                    Toast.makeText(context,""+error, Toast.LENGTH_SHORT).show();

                    if(code==200){
                        showScreen("","\t"+error);
//                        showScreen("\t"+error,"");
                    }  else{
                        showScreen("","支付失败,请重刷");
                    }
                }
                    //清空上次的刷卡记录
//                    setCardnull();
                }
            });
        }
    }
    private void showScreen(String title,String content){
        SunmiSdkManage.getInstance().showPrice(title,
                content,sunmiBack);
    }

    private ISendCallback sunmiBack=new ISendCallback() {
        @Override
        public void onSendSuccess(long taskId) {
            myHandler.postDelayed(delayRun,Constant.TIME_SCREEN_JUMP);
        }

        @Override
        public void onSendFail(int errorId, String errorInfo) {
        }

        @Override
        public void onSendProcess(long totle, long sended) {
        }
    };
    private void setCardnull(){
        nonce_str=0x0;
        on_card="";
    }
    Handler myHandler=new Handler();
    Runnable delayRun=new Runnable() {
        @Override
        public void run() {
            SunmiSdkManage.getInstance().showWelcomImg();
        }
    };
}
